package club.itstudio.IContainer.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;

public class Encrypt {
    private static final String Transformation = "AES/ECB/PKCS5Padding";
    private static final String AESEncrypt = "AES";
    public static final String AESKey = "43heelcm6395lepi";

    public static String encAES(String data, String key) {
        String result = "";
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(AESEncrypt);
            keyGenerator.init(128);
            Cipher cipher = Cipher.getInstance(Transformation);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), AESEncrypt));
            byte[] b = cipher.doFinal(data.getBytes());
            result = Base64.encodeBase64String(b);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String decAES(String data, String key) {
        String result = "";
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(AESEncrypt);
            keyGenerator.init(128);
            Cipher cipher = Cipher.getInstance(Transformation);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), AESEncrypt));
            byte[] encryptBytes = Base64.decodeBase64(data);
            byte[] decryptBytes = cipher.doFinal(encryptBytes);
            result = new String(decryptBytes);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        return result;
    }
}
